package com.qm.console.component.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

public class TicketHttp {

    private static Logger logger = LoggerFactory.getLogger(TicketHttp.class);


    public static final String POST = "POST";

    public static final String GET = "GET";

    public static final String UTF8 = "UTF-8";

    public static final String GBK = "GBK";

    public static final String GB2312 = "GB2312";

    public static String getResponse(String url, String method, String encoding,String params, int timeout) {
        logger.info("开始发送请求url{} params={}",new Object[]{url,params});
        OutputStream out = null;
        InputStream in = null;

        StringBuilder body = new StringBuilder();
		/*for(String key:params.keySet()) {
			body.append(key).append("=").append(params.get(key)).append("&");
		}

		if(body.toString().endsWith("&")) {
			body = body.deleteCharAt(body.toString().length()-1);
		}*/
        body.append(params);


        try {
            URL postUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) postUrl
                    .openConnection();
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            if(!"GET".equals(method)) {
                conn.setDoOutput(true);
            }
            conn.setDoInput(true);
            conn.setRequestMethod(method);
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(true);
            conn.setConnectTimeout(timeout);
            conn.setReadTimeout(timeout);
            conn.connect();
            if(!"GET".equals(method)) {
                if(!body.toString().isEmpty()) {
                    out = conn.getOutputStream();
                    out.write(body.toString().getBytes());
                    out.flush();
                }
            }
            in = conn.getInputStream();
            String result = read(in, encoding);
            logger.info("请求返回result={}",result);
            return result;
        } catch (MalformedURLException e) {
            logger.info("请求地址有误, url:" + url, e);
            throw new RuntimeException("请求地址有误, url:" + url);
        } catch (Exception e) {
            logger.info("IO错误,url:" + url + ",body:" + body, e);
            throw new RuntimeException("请求地址有误, url:" + url);
        } finally {
            close(in);
            close(out);
        }
    }

    public static String POST(String url, Map<String, String> params,
                              Map<String, String> requestProperties,String charsetName) throws IOException {
        logger.info("请求shishicai.cn:url="+url);
        URL shi = new URL(url);
        HttpURLConnection uc = (HttpURLConnection) shi.openConnection();
        uc.setReadTimeout(4000);
        uc.setConnectTimeout(10000);
        uc.setDoOutput(true);
        uc.setDoInput(true);
        uc.setRequestMethod("POST");
        uc.setUseCaches(false);
        uc.setInstanceFollowRedirects(true);
        if ((null!=requestProperties)&&(!requestProperties.isEmpty())) {
            for (Map.Entry<String, String> entry : requestProperties.entrySet()) {
                uc.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }

        uc.connect();

        StringBuilder req = new StringBuilder();
        if (!params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                req.append(entry.getKey()).append("=").append(entry.getValue())
                        .append("&");
            }
            if (req.toString().endsWith("&")) {
                req = req.deleteCharAt(req.length() - 1);
            }
        }

        OutputStream out = uc.getOutputStream();
        out.write(req.toString().getBytes());
        BufferedReader in = new BufferedReader(new InputStreamReader(
                uc.getInputStream(), charsetName), 1024 * 1024);
        String line;
        String sTotalString = "";
        while ((line = in.readLine()) != null) {
            sTotalString += line;
        }
        return sTotalString;

    }

    public static String read(InputStream in, String encoding) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, encoding));
            StringBuilder builder = new StringBuilder();
            String line = null;
            while(null != (line = reader.readLine())) {
                builder.append(line);
            }
            return builder.toString();
        } catch(Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            close(in);
        }
    }

    private static void close(InputStream in) {
        if(null != in) {
            try {
                in.close();
            } catch(Exception e) {
            }
        }
    }

    private static void close(OutputStream out) {
        if(null != out) {
            try {
                out.close();
            } catch(Exception e) {

            }
        }
    }
}
